<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2024/4/10
 * Time: 12:01
 */

namespace plugin\admin\app\logic\novel;


use app\common\lib\Common;
use app\common\lib\RedisQueue;
use app\common\lib\Spreadsheet;
use app\common\lib\TencentCos;
use app\exception\IndexException;
use app\model\douyin\CooperateAppidModel;
use plugin\admin\app\common\Constant;
use plugin\admin\app\exception\AdminException;
use plugin\admin\app\logic\BaseLogic;
use plugin\admin\app\model\image\ImageCommandPlanModel;
use plugin\admin\app\model\novel\NovelBusinessModel;
use plugin\admin\app\model\novel\NovelChapterModel;
use plugin\admin\app\model\novel\NovelSpreadModel;
use plugin\admin\app\model\plan\PromotionPlanModel;
use support\Request;
use support\Response;

class NovelLogic extends BaseLogic
{
    protected static $instance;

    public function __construct()
    {
        $this->model = new NovelSpreadModel();
    }

    public static function getInstance()
    {
        //        if(is_object(self::$instance)){
//            return self::$instance;
//        }

        return new self();
    }

    public function select(Request $request): Response
    {
        //更新方案数量
        $this->updatePlanNums();

        $field = $request->input('field');
        if($field==false){
            $request->inputSet('field','id');
            $request->inputSet('order','desc');
        }

        if($request->input('is_online')){
            $spreadType = $request->input('spread_type');
            $bWhere = ['status'=>1,'isdel'=>0];
            $spreadType>0 && $bWhere['spread_type'] = $spreadType;
            $businessIds = NovelBusinessModel::getInstance()->getWhere($bWhere)->pluck('id')->toArray();
            $novelSns = PromotionPlanModel::getInstance()->getWhere(['status'=>1,'isdel'=>0,['part_nums','>',0]])->pluck('novel_sn')->toArray();
            $request->inputSet('business_id',['in',$businessIds]);
            $request->inputSet('novel_sn',['in',$novelSns]);
            $request->inputSet('status',1);
        }
        $request->inputSet('isdel','0');
        return parent::select($request);
    }

    protected function formatNormal($items, $total): Response
    {
        $underStatusMap = [
            '1'=>'上架',
            '2'=>'下架',
        ];
        $taskStatusMap = [
            '0'=>'无',
            '1'=>'待审核',
            '2'=>'已上线',
            '3'=>'已下架',
            '4'=>'审核不通过',
        ];
        $settleTypeMap = [
            '0'=>'无',
            '1'=>'广告分成',
            '2'=>'支付分成',
            '3'=>'支付分成绑定',
            '4'=>'新增日活用户',
            '14'=>'付费分佣结算',
        ];

        $platformMap = Constant::PLATFORM_MAP;
        $businessMap = $this->getListMapById(NovelBusinessModel::getInstance(),$items,'business_id','id');
        $AiImagePlanMap = $this->getListMapById(ImageCommandPlanModel::getInstance(),$items,'ai_image_command_id','id');
        foreach($items as &$val){
            $val['under_status'] = $underStatusMap[$val['under_status']]??$val['under_status'];
            $val['task_status'] = $taskStatusMap[$val['task_status']]??$val['task_status'];
            $val['task_settle_type'] = $settleTypeMap[$val['task_settle_type']]??$val['task_settle_type'];
            $val['business_name'] = $businessMap[$val['business_id']]['name']??'';

            $val['platform_text'] = $platformMap[$val['platform']]??'';
            $val['is_end'] = $val['is_end']==1?'完结':'连载';
            $val['payment_allocate_ratio'] = $val['payment_allocate_ratio'] ? ($val['payment_allocate_ratio']/100).'%' : '0';

            $val['ai_image_template_name'] = $AiImagePlanMap[$val['ai_image_command_id']]['name']??'';
        }
        return parent::formatNormal($items, $total);
    }

    /**
     * 格式化下拉列表
     * @param $items
     * @return Response
     */
    protected function formatSelect($items): Response
    {
        $formatted_items = [];
        foreach ($items as $item) {
            $formatted_items[] = [
                'name' => $item->title ?? $item->name ?? $item->novel_sn,
                'value' => $item->novel_sn
            ];
        }
        return  json(['code' => 0, 'msg' => 'ok', 'data' => $formatted_items]);
    }

    public function insert(Request $request): Response
    {
        return parent::insert($request);
    }

    public function update(Request $request): Response
    {
        return parent::update($request);
    }

    public function delete(Request $request): Response
    {
        return parent::isDelete($request);
    }

    public function upload(Request $request): Response
    {
        $file = current($request->file());
        if ($file && $file->isValid()) {
            $ext = strtolower($file->getUploadExtension());
            if (!in_array($ext, ['xlsx'])) {
                throw new AdminException(4020, '仅支持 xlsx格式');
            }
        }

        //获取合作商家的appid
        $cooperateAppidMap = CooperateAppidModel::getInstance()->getWhere(['isdel'=>0,'platform'=>1])->pluck('appid','name')->toArray();

        $data = Spreadsheet::getInstance()->readExcelFile($file->getRealPath());
        unset($data[1]);

        $ids = [];
        foreach($data as $key=>$val){
            $val = array_map('trim', $val);

            $novelFirst = false;
            if(!empty($val[1])){
                $novelFirst = $this->model->getWhere(['task_id'=>$val[1],'task_status'=>2,'isdel'=>0])->first();
            }elseif(!empty($val[2])){
                $name = Common::filterCharacter($val[2]);
                $appid = $cooperateAppidMap[$val[0]];

                $where = ['app_id'=>$appid,'task_status'=>2,'isdel'=>0];
                $novelData = $this->model->getWhere($where)->orderBy('payment_allocate_ratio','asc')->get();
                foreach($novelData as $novel){
                    $title = Common::filterCharacter($novel['title']);
                    if($name==$title){
                        $novelFirst = $novel;
                        break;
                    }
                }
            }

            if($novelFirst==false){
                continue;
            }

            //封面图处理
            if(!empty($val[3]) && empty($novelFirst->main_image)){
                try{
                    $mainImageFileName = substr(md5(Common::getRequestId()),-26).'.png';
                    $res = TencentCos::getInstance()->uploadLocalFile($val[3],'novel',$mainImageFileName);
                    if(isset($res['Location'])){
                        $novelFirst->main_image = 'https://'.$res['Location'];
                    }
                }catch (\Exception $e){}
            }

            !empty($val[4]) && $novelFirst->labels = implode(',',explode('、',$val[4]));
            !empty($val[5]) && $novelFirst->desc = $val[5];

            $number = (int) NovelChapterModel::getInstance()->getWhere(['novel_sn'=>$novelFirst->novel_sn,'isdel'=>0])->count();
            if(!empty($val[6])){
                NovelChapterModel::getInstance()->insert(
                    [
                        'novel_sn'=>$novelFirst['novel_sn'],
                        'number'=>$number+1,
                        'name'=>'第'.($number+1).'章',
                        'original_content'=>$val[6],
                        'status'=>1
                    ]
                );
            }

            $novelFirst->status = 0;
            $novelFirst->save();

            $ids[] = $novelFirst['id'];
        }
        return $this->json(0,'ok',['ids'=>$ids]);
    }

    public function upload2(Request $request): Response
    {
        $file = current($request->file());
        if ($file && $file->isValid()) {
            $ext = strtolower($file->getUploadExtension());
            if (!in_array($ext, ['xlsx'])) {
                throw new AdminException(4020, '仅支持 xlsx格式');
            }
        }

        $data = Spreadsheet::getInstance()->readExcelFile($file->getRealPath());
        unset($data[1]);

        $bookids = array_filter(array_column($data,0));
        $businessId = 777;
        $where = [
            'data_source_key'=>'excel',
            'data_source_id'=>0,
            'business_id'=>$businessId,
            ['book_id','in',$bookids],
            'isdel'=>0
        ];
        $bookids = NovelSpreadModel::getInstance()->getWhere($where)->pluck('book_id')->toArray();

        $ids = [];
        foreach($data as $key=>$val){
            $val = array_map('trim', $val);
            if(empty($val[0])){
                continue;
            }
            if(in_array($val[0],$bookids)){
                continue;
            }

            //开始插入新数据
            $maxId =  NovelSpreadModel::getInstance()->getWhere([['novel_sn','>',0]])->max('novel_sn');
            $novelSn = Common::getSnCode($maxId,'50',3,1);
            $insert = [
                'novel_sn'=>$novelSn,
                'title'=>!empty($val[1])?$val[1].'(短)':'',
                'business_id'=>$businessId,
                'desc'=>'',
                'labels'=>$val[5]??'',
                'data_source_key'=>'excel',
                'data_source_id'=>0,
                'start_time'=>date('Y-m-d H:i:s'),
                'first_category'=>$val[3]??'',
                'second_category'=>$val[4]??'',
                'words_num'=>$val[2]??0,
                'operate_tags'=>$val[5]??'',
                'book_id'=>$val[0],
                'status'=>0,
                'spread_type'=>2,
                'under_status'=>1,
                'platform'=>4,
                'lang'=>'cn',
            ];
            $id = NovelSpreadModel::getInstance()->insertGetId($insert);
            $ids[] = $id;
        }
        return $this->json(0,'ok',['ids'=>$ids]);
    }

    public function customTags(Request $request): Response
    {
        $ids = $request->input('ids');
        if(empty($ids)){
            throw new IndexException(4020,'请选择数据');
        }
        $customTags = $request->input('custom_tags');
        if(empty($customTags)){
            throw new IndexException(4020,'标签不能为空');
        }
        $ids = explode(',',$ids);

         $this->model->getWhere([['id','in',$ids]])->update(['custom_tags'=>$customTags]);

         return $this->json('0','ok',[]);
    }

    public function generatePlan(Request $request): Response
    {
        $ids = $request->input('ids');
        if(empty($ids)){
            throw new IndexException(4020,'请选择小说');
        }
        $commandId = $request->input('ai_image_command_id');

        if(empty($commandId)){
            throw new IndexException(4020,'请选择生图指令');
        }
        $novelIds = explode(',',$ids);
        $prefix = $request->input('prefix');

        //生成唯一的请求id
        $requestId = Common::getRequestId();

        // 队列名
        $queue = 'batchGeneratePlan';
        // 数据，可以直接传数组，无需序列化
        $data = ['requestid'=>$requestId,'novel_ids'=>$novelIds,'ai_image_command_id'=>$commandId,'prefix'=>$prefix];
        // 投递消息
        RedisQueue::getInstance()->sendQueue($queue, $data);

        return $this->json('0','ok',['requestid'=>$requestId]);
    }

}